package com.todoit.wavebot.server;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.todoit.wavebot.util.JdoUser;
import com.todoit.wavebot.util.PMF;
import com.todoit.wavebot.util.TodoitTask;
import com.todoit.wavebot.util.TodoitTaskList;
import com.google.appengine.api.xmpp.JID; 
import com.google.appengine.api.xmpp.Message; 
import com.google.appengine.api.xmpp.MessageBuilder; 
import com.google.appengine.api.xmpp.MessageType; 
import com.google.appengine.api.xmpp.XMPPService; 
import com.google.appengine.api.xmpp.XMPPServiceFactory; 
import java.util.List;
import javax.jdo.Query;


public class CronReminderServlet extends HttpServlet {
	
	private PersistenceManager pm = PMF.get().getPersistenceManager();

	private static final XMPPService xmppService = 
	      XMPPServiceFactory.getXMPPService(); 

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
    	
    	TodoitTaskList pmTaskList, myTaskList;

    	response.setContentType("text/plain");
    	
    	JdoUser pmJdoUser, myJdoUser;
    	String DebugUser = "coutal@gmail.com";
    	
    	// ostensibly, iterate over all keys from the JdoUser datastore.
    	// for manual triggering, just read the user from principal.
    	// for demo, assume its my ID. 
    	
    	// try to get the task list from the persistence engine
    	try {
    		// detaching is the key word. why isn't it default behavior?
    		// the gods of programming know.
    		while (pm.isClosed())
    		{
    			pm = PMF.get().getPersistenceManager(); // give this a shot.
    		}
    		// sendXmppMessage(DebugUser, "Getting the object. Debug: "+ pm.getDetachAllOnCommit());
    		pmJdoUser = pm.getObjectById(JdoUser.class, "coutal@gmail.com");
    		// sendXmppMessage(DebugUser, "We really really want it.");
    		pm.retrieve(pmJdoUser);
    		pm.makeTransient(pmJdoUser);
    		// sendXmppMessage(DebugUser, "Yes, and its task list too.");
    		pm.makeTransientAll(pmJdoUser.getTaskList());
    		// myJdoUser = pm.detachCopy(pmJdoUser);
    		// sendXmppMessage(DebugUser, "Now can we please, god forbid, use it?");
    		myTaskList = (TodoitTaskList) pmJdoUser.getTaskList();
    		// sendXmppMessage(DebugUser, "hopefully finally made transient.");
    		// are we rid of the black ORM weak-reference magic? not yet...
    		// 10 things i hate about programming...
    		response.getWriter().print("Debug: got our task list.");
    		
    	}
    	catch (JDOObjectNotFoundException j)
    	{
   			myTaskList = new TodoitTaskList();
   			myJdoUser = new JdoUser("coutal@gmail.com", null, myTaskList);
   			pm.makePersistentAll(myJdoUser.getTaskList());
   			pm.makePersistent(myJdoUser);
   			response.getWriter().println("Debug: creation of persistent task object.");
    	};
   			
   		
        response.getWriter().println("Debug: manual invocation of cron service");
        //sendXmppMessage(DebugUser, "Going to iterate over the list.");
        
    	for (TodoitTask t : myTaskList)
    	{
    		if (t.isOverdue())
    		{
    			sendXmppMessage(t.owner, "Task ID (" + t.id + ") - " + t.title
    					+ " - is overdue! consider working on it soon.");
    			response.getWriter().println("Debug: sent a task notice for task ID " + t.id + ".");
    		}
    	}
    	
    	// this IS needed, and perhaps now it will write the goddamn thing too.
   		pm.close(); 
    };
    
    private void sendXmppMessage(String jid, String body) {
	    Message reply = new MessageBuilder()
	        .withRecipientJids(new JID(jid))
	        .withMessageType(MessageType.NORMAL)
	        .withBody(body)
	        .build();

	    xmppService.sendMessage(reply);
	  }

}
